function isValidDate(d) {
    if ( Object.prototype.toString.call(d) !== "[object Date]" )
		return false;
    return !isNaN(d.getTime());
}

// Logic inspired from http://snipplr.com/view/4086/

function calcBusinessDaysDiff(dDate1, dDate2) { // input given as Date objects

    var iWeeks, iDateDiff, iAdjust = 0;

    if (dDate2 < dDate1) return -1; // error code if dates transposed

    var iWeekday1 = dDate1.getDay(); // day of week
    var iWeekday2 = dDate2.getDay();

    iWeekday1 = (iWeekday1 == 0) ? 7 : iWeekday1; // change Sunday from 0 to 7
    iWeekday2 = (iWeekday2 == 0) ? 7 : iWeekday2;

    if ((iWeekday1 > 5) && (iWeekday2 > 5)) iAdjust = 1; // adjustment if both days on weekend

    iWeekday1 = (iWeekday1 > 5) ? 5 : iWeekday1; // only count weekdays
    iWeekday2 = (iWeekday2 > 5) ? 5 : iWeekday2;

    // calculate differnece in weeks (1000mS * 60sec * 60min * 24hrs * 7 days = 604800000)
    iWeeks = Math.floor((dDate2.getTime() - dDate1.getTime()) / 604800000)

    if (iWeekday1 <= iWeekday2) {
        iDateDiff = (iWeeks * 5) + (iWeekday2 - iWeekday1)
    } else {
        iDateDiff = ((iWeeks + 1) * 5) - (iWeekday1 - iWeekday2)
    }

    iDateDiff -= iAdjust // take into account both days on weekend

    return (iDateDiff);

}


// Logic inspired from http://lists.evolt.org/pipermail/javascript/2002-September/003983.html

function addBusinessDays(dDate,days) { // dDate = starting date, days = no. working days to add.
    var temp_date = new Date();
    var i = 0;
    var iDaysToAdd = 0;
    var iPlusMinus = days >= 0 ? 1 : -1

    while (i < Math.abs(Math.floor(days))){
        temp_date = new Date(dDate.getTime() + (iPlusMinus * iDaysToAdd*24*60*60*1000));
        //0 = Sunday, 6 = Saturday, if the date not equals a weekend day then increase by 1

        if ((temp_date.getDay() != 0) && (temp_date.getDay() != 6)){
            i+=1;
        }

        if ((iPlusMinus==1 && temp_date.getDay() == 5) || (iPlusMinus==-1 && temp_date.getDay() == 1))
            // for +, on Friday, add 3 days to skip to next Monday; for -, on Monday, minus 3 days to skip to last Friday
                iDaysToAdd += 3
        else
                iDaysToAdd += 1;
    }
    return new Date(dDate.getTime() + (iPlusMinus * iDaysToAdd*24*60*60*1000));
}
